/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.deservel.wxopen.service.Impl;

import com.deservel.wxopen.common.utils.HttpsUtils;
import com.deservel.wxopen.constant.UrlConsts;
import com.deservel.wxopen.model.userinfo.SNSUserInfo;
import com.deservel.wxopen.model.userinfo.WeixinOauth2Token;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;

/**
 * 微信网页授权
 *
 * @author DeserveL
 * @date 2017/7/10 14:44
 * @since 1.0.0
 */
@Service
public class OAuth2ServiceImpl {

    private static Logger log = LoggerFactory.getLogger(CoreServiceImpl.class);

    //可以不一一对应
    private ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    @Autowired
    UrlConsts urlConsts;

    /**
     * 获取网页授权凭证
     *
     * @param code
     * @return WeixinAouth2Token
     */
    public WeixinOauth2Token getOauth2AccessToken(String code) {
        // 拼接请求地址
        String requestUrl = urlConsts.getAccess_token_web();
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        String jsonObject = HttpsUtils.sendHttpRequest(HttpsUtils.METHOD_GET, requestUrl);
        if (null != jsonObject) {
            HashMap rs = null;
            try {
                rs = objectMapper.readValue(jsonObject, new TypeReference<HashMap<String, Object>>() {
                });
                Object errcode = rs.get("errcode");
                if (errcode != null) {
                    log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", rs.get("errcode"), rs.get("errmsg"));
                    return null;
                } else {
                    WeixinOauth2Token weixinOauth2Token = objectMapper.readValue(jsonObject, WeixinOauth2Token.class);
                    return weixinOauth2Token;
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return null;
    }

    /**
     * 通过网页授权获取用户信息
     *
     * @param accessToken 网页授权接口调用凭证
     * @param openId      用户标识
     * @return SNSUserInfo
     */
    @SuppressWarnings({"deprecation", "unchecked"})
    public SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
        // 拼接请求地址
        String requestUrl = urlConsts.getUserinfo();
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        String jsonObject = HttpsUtils.sendHttpRequest(HttpsUtils.METHOD_GET, requestUrl);
        if (null != jsonObject) {
            HashMap rs = null;
            try {
                rs = objectMapper.readValue(jsonObject, new TypeReference<HashMap<String, Object>>() {
                });
                Object errcode = rs.get("errcode");
                if (errcode != null) {
                    log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", rs.get("errcode"), rs.get("errmsg"));
                    return null;
                } else {
                    SNSUserInfo snsUserInfo = objectMapper.readValue(jsonObject, SNSUserInfo.class);
                    return snsUserInfo;
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return null;
    }
}
